"""
@Author  : 康帅
@Time    : 2021/6/30 11:22
@Function: collections
"""

from collections import defaultdict, Counter, ChainMap
import json


def not_check_dict_is_exit():
    """
    defaultdict
    与dict类型不同，你不需要检查key是否存在
    :return:
    """
    colours = (
        ('Yasoob', 'Yellow'),
        ('Ali', 'Blue'),
        ('Arham', 'Green'),
        ('Ali', 'Black'),
        ('Yasoob', 'Red'),
        ('Ahmed', 'Silver'),
    )

    favourite_colours = defaultdict(list)
    for name, colour in colours:
        favourite_colours[name].append(colour)

    print(json.dumps(favourite_colours))


def counter_data():
    """
    Counter是一个计数器，
    它可以帮助我们针对某项数据进行计数
    :return:
    """
    colours = (
        ('Yasoob', 'Yellow'),
        ('Ali', 'Blue'),
        ('Arham', 'Green'),
        ('Ali', 'Black'),
        ('Yasoob', 'Red'),
        ('Ahmed', 'Silver'),
    )

    favs = Counter(name for name, colour in colours)
    print(json.dumps(favs))


def file_count():
    """
    利用Counter做文件统计
    :return:
    """
    with open('filename', 'rb') as f:
        line_count = Counter(f)
    print(json.dumps(line_count))


def list_max_value():
    """
    序列中出现次数最多的元素
    :return:
    """
    words = [
        'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
        'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
        'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
        'my', 'eyes', "you're", 'under'
    ]
    word_counts = Counter(words)
    # 出现频率最高的3个单词
    top_three = word_counts.most_common(3)
    print(top_three)


def collections_chain_map():
    """
    合并多个字典或映射:
        逻辑上是将多个字典合并为一个字典
        这些字典并不是真正的合并到一起
        ChainMap类只是在内部创建了一个容纳这些字典的列表
        并重新定义了一些常见的字典操作来遍历这个列表
    :return:
    """
    a = {'x': 1, 'z': 3}
    b = {'y': 2, 'z': 4}
    c = ChainMap(a, b)
    # 先从a中找，如果找不到再在b中找
    print(c['x'])  # 1 from a
    print(c['y'])  # 2 from b
    print(c['z'])  # 3 from a

    # ChainMap 对于编程语言中的作用范围变量（比如 globals , locals 等）是非常有用的
    values = ChainMap()
    values['x'] = 1
    # 添加新映射
    values = values.new_child()
    values['x'] = 2
    # 添加新映射
    values = values.new_child()
    values['x'] = 3
    print("------values------", values)
    print("add_mapping_value", values['x'])

    # 丢弃最后的映射
    values = values.parents
    print("remove_mapping_value", values['x'])  # 2
    # 丢弃最后的映射
    values = values.parents
    print("remove_mapping_value", values['x'])  # 1

    # 可使用update代替ChainMap,产生一个新的字典将a和b组合
    new_dict = dict(b)
    new_dict.update(a)
    print(new_dict)
    print(id(a))
    print(id(b))
    print(id(new_dict))


if __name__ == '__main__':
    not_check_dict_is_exit()
    counter_data()
    list_max_value()
    collections_chain_map()
